//
//  PersonCenterViewController.m
//  hello mui
//
//  Created by zhangtao on 15/9/14.
//  Copyright (c) 2015年 zt.td. All rights reserved.
//

#import "PersonCenterViewController.h"
#import "PersonInfoViewController.h"
#import "ChangeClassViewController.h"
#import "SystemViewController.h"
#import "LoginAndRegistViewController.h"
#import "WXApi.h"
#import "TencentOpenAPI/QQApiInterface.h"

#import "DDifficultViewController.h"
#import "LLListenViewController.h"
#import "ScanViewController.h"
#import "Upload.h"
#import "CollectViewController.h"

#import "ClassmaterViewController.h"
#import "FriendsViewController.h"
#import "ActivityViewController.h"
enum{
    CLASSMATER = 0,
    FRIEND   = 1,
    ACTIVITY = 2,

    
};
//#import <TencentOpenAPI/TencentMessageObject.h>

@interface PersonCenterViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

{
    
}
@property (weak, nonatomic) IBOutlet UIImageView *headOut;
@property (weak, nonatomic) IBOutlet UIButton *addPic;
@property (strong, nonatomic) IBOutlet UIButton *loginAndRegistBtn;
@property(nonatomic)enum WXScene currentScess;
@property (weak, nonatomic) IBOutlet UIView *viewOne;
@property (weak, nonatomic) IBOutlet UIView *viewTwo;
@property (weak, nonatomic) IBOutlet UIView *viewThree;
@property (weak, nonatomic) IBOutlet UIButton *personInfo;
@property (weak, nonatomic) IBOutlet UIButton *changeGrade;
@property (weak, nonatomic) IBOutlet UIButton *myCollect;
@property (weak, nonatomic) IBOutlet UIButton *classMater;
@property (weak, nonatomic) IBOutlet UIButton *shareFriend;
@property (weak, nonatomic) IBOutlet UIButton *activity;

@property (weak, nonatomic) IBOutlet UIImageView *toRegistPic;
@end

@implementation PersonCenterViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
//    self.tabBarController.tabBar.hidden = NO;
    if (!NSUSER_DEF(@"USERID")) {
        [_loginAndRegistBtn addTarget:self action:@selector(loginAndRegist) forControlEvents:UIControlEventTouchUpInside];
        self.toRegistPic.hidden = NO;
    }else{
        if (!NSUSER_DEF(@"NICKNAME")) {
            [_loginAndRegistBtn setTitle:@"主人" forState:UIControlStateNormal];

        }else{
           [_loginAndRegistBtn setTitle:NSUSER_DEF(@"NICKNAME") forState:UIControlStateNormal];
        }
        self.toRegistPic.hidden = YES;
    }
    
}
- (IBAction)webBtn:(UIButton *)sender {
    if (NSUSER_DEF(@"USERID")) {
        if (sender.tag == CLASSMATER) {
            ClassmaterViewController *mater = [self.storyboard instantiateViewControllerWithIdentifier:@"classmater"];
            [mater setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:mater animated:YES];
        }else if (sender.tag == FRIEND){
            FriendsViewController *friend = [self.storyboard instantiateViewControllerWithIdentifier:@"friend"];
            [friend setHidesBottomBarWhenPushed: YES];
            [self.navigationController pushViewController:friend animated:YES];
        }else if (sender.tag == ACTIVITY){
            ActivityViewController *activity = [self.storyboard instantiateViewControllerWithIdentifier:@"activity"];
            [activity setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:activity animated:YES];
        }
    }else{
        [ToolObjc showMessage:@"您还没有登录"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    [_activity setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 5, 50)];
       
    NSString *imagePath = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"HEADIMG")];
    if (imagePath.length>10) {
        NSLog(@"??????????%@",imagePath);
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
                  UIImage *urlImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]]];
        NSLog(@"!!!!!___headerImage22");
            [self.addPic setImage:urlImage forState:UIControlStateNormal];
//        NSLog(@"!!!!!___headerImage3333");
//
//    });
//
    } else{
        
        [_addPic setImage:[UIImage imageNamed:@"qbr"] forState:UIControlStateNormal];
        }

    _viewOne.layer.borderColor = _viewTwo.layer.borderColor = _viewThree.layer.borderColor = rgb_box;
    _viewOne.layer.borderWidth = _viewTwo.layer.borderWidth = _viewThree.layer.borderWidth = 1;
    _addPic.layer.cornerRadius = _addPic.frame.size.height/2.0f-3.0f;
    _addPic.layer.masksToBounds
    = YES;

    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.tabBarItem.image = [UIImage imageNamed:@"1.png"];
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"home"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.tabBarItem.badgeValue=@"5";
     [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIFont systemFontOfSize:20.0],UITextAttributeFont,nil]];
    

    [self showInfo];
}
- (void)loginAndRegist{
    LoginAndRegistViewController *login = [self.storyboard instantiateViewControllerWithIdentifier:@"loginAndRegist"];
    [self presentViewController:login animated:NO completion:nil];
}

-(void)showInfo{
//    NSString *str = NSUSER_DEF(@"USERHEADER");
    NSUSER_DEF(@"NICKNAME");
//    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str]]];
//    if (image == nil) {
//        [_addPic setImage:[UIImage imageNamed:@"qbr"] forState:UIControlStateNormal];
//        _nickName.text = @"小凰";
//        return;
//    }else{
//    [_addPic setImage:image forState:UIControlStateNormal];
//    }
    
    _nickName.text =  NSUSER_DEF(@"NICKNAME");
    
}

//收藏
- (IBAction)myShouCang:(id)sender {
    if (!NSUSER_DEF(@"USERID")) {
        [ToolObjc showMessage:@"您还未登陆"];
    }else{
        CollectViewController *collect = [[CollectViewController alloc]initWithNibName:@"CollectViewController" bundle:nil];
//        [self presentViewController:collect animated:YES completion:nil];
        [collect setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:collect animated:YES];
    
    }
}

//个人信息
- (IBAction)personInfo:(id)sender {

    if (!NSUSER_DEF(@"USERID")) {
        [ToolObjc showMessage:@"您还未登陆"];
    }else{

    
    PersonInfoViewController *info = [[PersonInfoViewController alloc]initWithNibName:@"PersonInfoViewController" bundle:nil];
        [info setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:info animated:YES];
    }
}

- (IBAction)system:(id)sender {
    SystemViewController *system = [[SystemViewController alloc]initWithNibName:@"SystemViewController" bundle:nil];
    [system setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:system animated:YES];
}

//切换年级
- (IBAction)changeClass:(id)sender {
    if (!NSUSER_DEF(@"USERID")) {
        [ToolObjc showMessage:@"您还未登陆"];
    }else{
    
//                class.groupLabel.text = NSUSER_DEF(@"GROUP");
        
        NSString *path = @"personalCenter/getReadInfo";
        
        NSString *userId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"USERID")];
        
        NSDictionary *dic = @{@"userId":userId};
        NSDictionary *dicVal = @{@"userId":userId,@"bd_sig":[ToolObjc md5Str:dic]};
        
        [[HttpConnctionManager sharedInstance]requestParam:dicVal andUrl:path andSuccessedBlock:^(NSDictionary *succeedResult) {
            NSLog(@"asdf~~~~~~%@",[succeedResult valueForKey:@"shiName"]);
            NSUSER_DEF_NORSET([succeedResult stringWithFilted:@"gradeName"], @"GRADE");
            NSUSER_DEF_NORSET([succeedResult stringWithFilted:@"schoolName"], @"SCHOOL");
            NSUSER_DEF_NORSET([succeedResult stringWithFilted:@"shengName"], @"SHENG");
            NSUSER_DEF_NORSET([succeedResult stringWithFilted:@"shiName"], @"SHI");
            NSUSER_DEF_NORSET([succeedResult stringWithFilted:@"areaName"], @"AREA");
             NSUSER_DEF_NORSET([succeedResult stringWithFilted:@"termName"], @"DATA");
            NSString *address;
            if (NSUSER_DEF(@"SHENG")) {
                address = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"SHENG")];
                if (NSUSER_DEF(@"SHI")) {
                    address = [address stringByAppendingString:[NSString stringWithFormat:@"%@",NSUSER_DEF(@"SHI")]];
                    if (NSUSER_DEF(@"AREA")) {
                        address = [address stringByAppendingString:[NSString stringWithFormat:@"%@",NSUSER_DEF(@"AREA") ]];
                    }
                }
//                _groupLabel.text = address;
                NSUSER_DEF_NORSET(address, @"GROUP");
                NSLog(@"1111111111111");
            }

            NSLog(@"333333333333222222222");

            
            ChangeClassViewController *class = [[ChangeClassViewController alloc]initWithNibName:@"ChangeClassViewController" bundle:nil];
//            class.groupLabel.text = NSUSER_DEF(@"GROUP");
            [class setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:class animated:YES];
            NSLog(@"222222222222222222");

        } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
            
        }];
        
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)shareBtn:(id)sender {
//    
//    NSString *value = [[NSUserDefaults standardUserDefaults]valueForKey:@"SHARE"];
//    if (value == nil) {
//        NSLog(@"hele");
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"您还没有登录" message:@"请登陆后分享" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        
//        [alert show];
//        
//    }else{
//        if ([value isEqualToString:@"WeChat"]) {
//            [self WeChatShare];
//        }else if ([value isEqualToString:@"Tencent"]){
//            [self TencentShare];
//        }else{
//        
//            ///
//        }
//    }
}

//-(void)WeChatShare{
//    [WXApi registerApp:AppID withDescription:@"ztTest"];
//    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
//    req.text = shareText;
//    req.scene = WXSceneSession;  //聊天窗口
//    req.bText = YES;
//    [WXApi sendReq:req];
//    
//}
//
//-(void)TencentShare{
//    //开发者分享的文本内容
//    QQApiTextObject *txtObj = [QQApiTextObject objectWithText:[NSString stringWithFormat:@"%@",SHARE_TEXT]];
//    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
//    //将内容分享到qq
//    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
//    NSLog(@"~~~~~~~~~~~~~%d",sent);
//}

- (IBAction)function:(id)sender {
//    LLListenViewController *listen = [[LLListenViewController alloc]initWithNibName:@"LLListenViewController" bundle:nil];
//    [self presentViewController:listen animated:NO completion:nil];
}
- (IBAction)difficult:(id)sender {
//    ScanViewController *scan = [self.storyboard instantiateViewControllerWithIdentifier:@"scan"];
//    [self presentViewController:scan animated:NO completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)addPic:(UIButton *)sender {
    if (!NSUSER_DEF(@"USERID")) {
        [ToolObjc showMessage:@"您还未登陆"];
    }else{
    [self selectPhoto];
    }
}

-(void)selectPhoto{
    
    UIActionSheet *myActionSheet = [[UIActionSheet alloc]initWithTitle:@"选取图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"打开相机" otherButtonTitles:@"从相册选取", nil];
    [myActionSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        if (buttonIndex == 0) {
            [self takePhoto];
        }else if (buttonIndex == 1){
            [self LocalPhoto];
        }
    }];
}

//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        
        //        [self presentModalViewController:picker animated:YES];
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(110, 200, 100, 500)];
        label.backgroundColor = [UIColor redColor];
        [self.view addSubview:label];
    }
}


-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //设置选择后的图片可以被编辑
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    
    [self presentViewController:picker animated:YES completion:nil];
    //    [self presentModalViewController:picker animated:YES];
}
//压缩图片
- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize

{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return reSizeImage;
    
}
//用户确定选择
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    NSMutableDictionary * dict= [NSMutableDictionary dictionaryWithDictionary:editingInfo];
    
    [dict setObject:image forKey:@"UIImagePickerControllerEditedImage"];
    
    //直接调用3.x的处理函数
    [self imagePickerController:picker didFinishPickingMediaWithInfo:dict];
}

// 用户选择取消
- (void) imagePickerControllerDidCancel: (UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
    //[picker release];
}
//选择图片后处理图片
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    UIImage * images = [self reSizeImage:image toSize:CGSizeMake(image.size.width, image.size.height)];
    
    [self.addPic setImage:images forState:UIControlStateNormal];
    
    
    NSData *imageData
    = UIImageJPEGRepresentation(images, 0.0);
    [self upload:imageData];
    
    //将二进制数据生成UIImage
    UIImage *newimage = [UIImage imageWithData:imageData];
    [self saveImage:newimage WithName:@"image.jpg"];
    
    [ToolObjc upDataImage:imageData];
    
//    NSString *documentsPath = [self documentFolderPath];
    
    
   

    
//    Upload *upload = [[Upload alloc]init];
//    [upload Post:request andDic:dicVal withImage:documentsPath];
//    NSLog(@"%@",documentsPath);
    // [HttpRequestManager uploadImage:compressedImage httpClient:self.httpClient delegate:self];
}

//获取Documents路径
- (NSString *)documentFolderPath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}

//保存图片到Documents目录
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImageJPEGRepresentation(tempImage,0.0);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    
    NSLog(@"~~~!!!~~~!!!%@",fullPathToFile);
    
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
//    [self showPic:fullPathToFile];
}


//显示图片到页面
-(void)showPic:(NSString *)imagePath{
    NSUSER_DEF_NORSET(imagePath, @"LOCALUSERHEADER");

    UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];

    [self.addPic setImage:image forState:UIControlStateNormal];
//    self.userHeaderIV.image = image;// setImage:image forState:UIControlStateNormal];
//    [_addPic setImage:image forState:UIControlStateNormal];
}


-(void)upload:(NSData *)imageData{
        NSString *userId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"USERID")];
        
        NSDictionary *dics = @{@"userId":userId};
        NSDictionary *dic = @{@"userId":userId,@"bd_sig":[ToolObjc md5Str:dics]};
        NSString *path = @"http://182.92.117.144:8080/study-manager/login/uploadUserHeadImg";
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
        [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
        [manager.requestSerializer setValue:@"text/html" forHTTPHeaderField:@"content-Type"];
        //    AFURLResponseSerializationErrorDomain
        [manager POST:path parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:imageData name:@"headImg" fileName:@"123.jpg" mimeType:@"image/jpeg"];
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            
            NSLog(@"successUpLoad%@~~%@",[dic valueForKey:@"resMessage"],dic);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"失败%@",error);
        }];
        
        
    
}

@end
